package Blog

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/Blog"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"strconv"
)

//更新博客编辑
type UpdateBlog struct {
	controllers.MainController
}

type UpdateResp struct {
	BlogId   int
	Title    string //标题
	Context  string //内容
	Category string //类别
}

func (this *UpdateBlog) Post() {
	rd := redis.R.Conn
	defer rd.Close()
	//获取用户id
	uuid := this.Ctx.GetCookie("uuid")
	userid, err1 := rd.Get(uuid)
	if err1 != nil || userid == "" {
		body := map[string]interface{}{"code": 300, "data": map[string]interface{}{"msg": "用户不存在"}}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	var update UpdateResp
	err2 := decoder.Decode(&update)
	if err2 != nil {
		body := map[string]interface{}{"code": 301, "data": map[string]interface{}{"msg": "json解析失败"}}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//更新操作
	blogid := update.BlogId
	db := models.ConnDb()
	defer db.Close()
	//用户一致性检测
	var tb Blog.TBloginfo
	err3 := db.Where("blog_id = ?", blogid).Find(&tb).Error
	if err3 != nil {
		body := map[string]interface{}{"code": 302, "data": map[string]interface{}{"msg": "查找用户id不成功"}}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	uid, _ := strconv.Atoi(userid)
	if tb.UId == uid {
		err4 := db.Model(&tb).Where("blog_id = ?", blogid).Updates(Blog.TBloginfo{BlogContent: update.Context, BlogTitle: update.Title, Category: update.Category}).Error
		if err4 != nil {
			body := map[string]interface{}{"code": 303, "data": map[string]interface{}{"msg": "用户不对应"}}
			this.Data["json"] = body
			this.ServeJSON()
			return
		}
	} else {
		body := map[string]interface{}{"code": 304, "data": map[string]interface{}{"msg": "异常操作"}}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "data": map[string]interface{}{"msg": "操作成功"}}
	this.Data["json"] = body
	this.ServeJSON()
}
